﻿/*****************************************************************************
 * 此类继承框的AddonBase类目的是使B1Application的事件可以独立于B1Form之上，这样
 * 一些窗体的共同点可以提取出来集中进行处理。  
 * ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using BoAddonBiz_FreightForwarder.BusinessBase;
using System.Threading;

namespace BoAddonBiz_FreightForwarder
{
    public class CommonEvents : SAPBoAddon.B1AddonBase.AddonBase
    {
        #region Global Varialbe
        public IList<string> FormTypes = new List<string>();
        //Thread reportThread;//关闭报表时打开别处一个线程
        //Object mylock = new object();//锁
#if DEBUG
        private DateTime CurrentDatetime;
#endif
        private SAPbouiCOM.BoFormMode CurrentFormMode;
        private CommonEvents oCommon;
        #endregion
        #region 构造函数
        public CommonEvents(SAPbouiCOM.Application SBOAppication, SAPbobsCOM.Company SBOCompany)
            : base(SBOAppication, SBOCompany)
        {
            if (oCommon != null)
                return;

            this.B1FormDataEvent += new B1FormDataEventEventHandler(CommonEvents_B1FormDataEvent);
            this.B1ItemEvent += new B1ItemEventEventHandler(CommonEvents_B1ItemEvent);
            this.B1MenuEvent += new B1MenuEventEventHandler(CommonEvents_B1MenuEvent);
            this.B1RightClickEvent += new B1RightClickEventEventHandler(CommonEvents_B1RightClickEvent);
            #region 获取设置了更新属性
            foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (t.BaseType == typeof(SAPBoAddon.B1Form))
                {
                    if (!t.IsAbstract && t.IsClass)
                    {
                        object[] B1ClassAttributeList = t.GetCustomAttributes(typeof(ControlB1FormAttribute), true);
                        if (B1ClassAttributeList.Length > 0)
                        {
                            ControlB1FormAttribute B1FormAttribute = B1ClassAttributeList[0] as ControlB1FormAttribute;
                            if (B1FormAttribute.IsNew == true)
                            {
                                FormTypes.Add(B1FormAttribute.FormType);
                            }
                        }
                    }
                    else
                    {
                        foreach (Type tt in Assembly.GetExecutingAssembly().GetTypes())
                        {
                            if (!tt.IsClass) continue;
                            if (tt.BaseType == t)
                            {
                                object[] B1ClassAttributeList = tt.GetCustomAttributes(typeof(ControlB1FormAttribute), true);
                                if (B1ClassAttributeList.Length > 0)
                                {
                                    ControlB1FormAttribute B1FormAttribute = B1ClassAttributeList[0] as ControlB1FormAttribute;
                                    if (B1FormAttribute.IsNew == true)
                                    {
                                        FormTypes.Add(B1FormAttribute.FormType);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion
            oCommon = this;
        }
        #endregion
        #region Events
        void CommonEvents_B1FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo BusinessObjectInfo, ref bool BubbleEvent)
        {
            try
            {
                if (FormTypes.Contains(BusinessObjectInfo.FormTypeEx))
                {
                    if (BusinessObjectInfo.BeforeAction)
                    {
                        #region 窗体添加时再次获取流水码，保证流水码的正确  [获取流水号注释by WangPeng 2012-06-14]
                        if (BusinessObjectInfo.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE)
                        {
                            SAPbouiCOM.DBDataSource dbds = SBOApp.Forms.ActiveForm.DataSources.DBDataSources.Item(SBOApp.Forms.ActiveForm.Items.Item(SBOApp.Forms.ActiveForm.DataBrowser.BrowseBy).Specific.DataBind.TableName);
                            if (dbds.GetValue("U_Status", dbds.Offset).Trim() == "D")
                            {
                                SerialNumber.GetInstance().RecoveryNumber = dbds.GetValue("U_SerialNum", dbds.Offset).Trim();
                                SerialNumber.GetInstance().ExistsRecoveryNumber = true;
                            }
                        }
                        #endregion
                        #region 判断窗体字段是否允许为空
                        if (BusinessObjectInfo.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD || BusinessObjectInfo.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE)
                        {
                            ControlOrderEmpty(SBOApp.Forms.ActiveForm, ref BubbleEvent);
                        }
                        #endregion
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        void CommonEvents_B1ItemEvent(string FormUID, SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            try
            {
                if (pVal.BeforeAction)
                {
                    #region 数据所有权控制
                    if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_CHOOSE_FROM_LIST)
                    {
                        Utils.ChooseFormListAuthority(SBOApp.Forms.ActiveForm, pVal.FormTypeEx, ref BubbleEvent);
                    }
                    #endregion
                    #region 单击确定按钮时提示
                    ////单击确定按钮时提示
                    //if (pVal.ItemUID == "1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED && SBOApp.Forms.Item(pVal.FormUID).IsSystem == false)
                    //{
                    //    ClickOkButton(ref BubbleEvent);
                    //}
                    #endregion
                    #region 激活子窗体
                    //影响系统单据效率，暂时注掉
                    ////激活带有子窗体的窗体
                    //if (SBOApp.Forms.Count > 3)
                    //{
                    //    if (SBOApp.Forms.ActiveForm != null && (
                    //                pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_ACTIVATE ||
                    //                pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK ||
                    //                pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED ||
                    //                pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_CLOSE))
                    //    {
                    //        Utils.ActiveChildForm(SBOApp.Forms, pVal, SBOApp.Forms.ActiveForm, ref BubbleEvent);
                    //    }
                    //}
                    #endregion
                    #region 启动关闭报表窗体的线程
                    //if (pVal.FormTypeEx == "10004100" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD)
                    //{
                    //    lock (mylock)
                    //    {
                    //        if (reportThread != null)
                    //            if (reportThread.ThreadState != ThreadState.Running) reportThread.Start();
                    //    }
                    //}
                    #endregion
                    #region 列表框窗体关闭
                    //列表框对象窗体关闭
                    if (new string[] { "410000003", "10004100", "410000100" }.Contains(pVal.FormTypeEx) == false && pVal.FormTypeEx.StartsWith("110") && pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD && SBOApp.Forms.Item(pVal.FormUID).IsSystem)
                    {
                        ComboBoxListFormClose(FormUID);
                    }
                    #endregion
                    #region 窗体关闭
#if DEBUG
                    if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)
                    {
                        CurrentDatetime = DateTime.Now;
                    }
#endif
                    #endregion
                    #region 把对象的当前DocEntry写入到
                    if (FormTypes.Contains(pVal.FormTypeEx) && pVal.ItemUID == "1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED && pVal.FormMode == 3)
                    {
                        try
                        {
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
                            SAPbouiCOM.EditText oEdit = oForm.Items.Item(oForm.DataBrowser.BrowseBy).Specific;
                            oForm.DataSources.UserDataSources.Item("LastEntry").Value = oForm.DataSources.DBDataSources.Item(oEdit.DataBind.TableName).GetValue("DocEntry", 0).Trim();
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                            throw (ex);
                        }
                    }
                    #endregion
                    #region 控制单据状态
                    if (pVal.ItemUID == "7" && (pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT))
                    {
                        CurrentFormMode = (SAPbouiCOM.BoFormMode)pVal.FormMode;
                    }
                    #endregion
                    #region EditText控件焦点移出时，如果内容为空，自动清空对应Code字段（By Webb.Wen at 2012-05-03 15:30:47）
                    if (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD && pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)  /*防止退出B1时进入该代码块  added by WangPeng 2012-5-4*/
                    {
                        if (!SBOApp.Forms.ActiveForm.IsSystem && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)//事件之前捕获不到LOST_FOCUS事件，所以改成了Validate（真二）
                        {
                            SAPbouiCOM.Form oForm = Utils.GetForm(SBOApp, FormUID);// SBOApp.Forms.Item(FormUID);// SBOApp.Forms.ActiveForm;
                            if (oForm == null)
                            {
                                return;
                            }
                            if (oForm.Items.Item(pVal.ItemUID).Type == SAPbouiCOM.BoFormItemTypes.it_EDIT)
                            {
                                SAPbouiCOM.EditText item = oForm.Items.Item(pVal.ItemUID).Specific as SAPbouiCOM.EditText;
                                if (String.IsNullOrWhiteSpace(item.Value))
                                {
                                    if (item.DataBind.DataBound && !String.IsNullOrEmpty(item.DataBind.TableName))
                                    {
                                        string fieldName = item.DataBind.Alias.EndsWith("Name") ? item.DataBind.Alias.Replace("Name", "Code") : item.DataBind.Alias + "Code";
                                        SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(item.DataBind.TableName);
                                        IEnumerator enumerator = dbds.Fields.GetEnumerator();
                                        while (enumerator.MoveNext())
                                        {
                                            SAPbouiCOM.Field field = enumerator.Current as SAPbouiCOM.Field;
                                            if (field.Name == fieldName)
                                            {
                                                dbds.SetValue(fieldName, dbds.Offset, "");
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                }
                else
                {
                    #region 按写入DocEntry值查找到单据
                    if (FormTypes.Contains(pVal.FormTypeEx) && pVal.ActionSuccess && pVal.FormMode == 3 && pVal.ItemUID == "1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                    {
                        try
                        {
                            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
                            if (oForm.DataSources.UserDataSources.Item("LastEntry").Value.Length > 0)
                            {
                                FindForm();
                            }
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                            throw (ex);
                        }
                    }
                    #endregion
                    #region #DEBUG
#if DEBUG
                    if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)
                    {
                        TimeSpan ts = DateTime.Now - CurrentDatetime;
                        SBOApp.SetStatusBarMessage("调试运行时间：" + ts.TotalMilliseconds.ToString(), SAPbouiCOM.BoMessageTime.bmt_Short, false);
                    }
#endif
                    #endregion
                    #region 下拉列表框的新建功能
                    //下拉列表框的新建功能
                    if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && SBOApp.Forms.Item(FormUID).IsSystem == false)
                    {
                        ComboBoxHandle(pVal.FormTypeEx, FormUID, pVal.ItemUID, pVal.ColUID, pVal.Row);
                    }
                    #endregion
                    #region 键盘操作
                    //键盘操作
                    if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_KEY_DOWN)
                    {
                        if (pVal.CharPressed == 38 || pVal.CharPressed == 40)//↑键和↓键实现和点击一样的效果
                        {
                            #region ↑键和↓键实现和点击一样的效果
                            Utils.KeyboardShortcuts(SBOApp.Forms.ActiveForm, pVal.ItemUID, pVal.ColUID, pVal.Row, (Utils.BoKeyboardValue)pVal.CharPressed);
                            #endregion
                        }
                    }
                    #endregion
                    #region 获取流水码    deleted by WangPeng 2012-6-14
                    //if (pVal.ItemUID == "1" && pVal.ActionSuccess && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                    //{
                    //    if (SBOApp.Forms.ActiveForm.Mode == SAPbouiCOM.BoFormMode.fm_ADD_MODE)
                    //        SerialNumber.GetInstance().GetSerialNumberByProc(SBOApp.Forms.ActiveForm);
                    //}
                    #endregion
                    #region 控制单据状态
                    if (pVal.ItemUID == "7" && (pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT))
                    {
                        ControlOrderStatus();
                    }
                    #endregion
                    #region 发送消息
                    if (pVal.ItemUID == "btn_Send" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                    {
                        if (SBOApp.Forms.ActiveForm.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE)
                        {
                            if (SAPBoAddon.B1Assistant.Item.GetValue(SBOApp.Forms.ActiveForm, "7").ToString() == "R"
                                || (SBOApp.Forms.ActiveForm.TypeEx == B1FormTypes.ado_AVA_FF_AirOrderUsed && (SAPBoAddon.B1Assistant.Item.GetValue(SBOApp.Forms.ActiveForm, "7").ToString() == "P" || SAPBoAddon.B1Assistant.Item.GetValue(SBOApp.Forms.ActiveForm, "7").ToString() == "S"))
                                )
                            {
                                string ParentUID = SBOApp.Forms.ActiveForm.UniqueID;
                                SAPbouiCOM.Form messageForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_FF_MessageForm.srf", "", true);
                                messageForm.DataSources.UserDataSources.Item("ParentUID").Value = ParentUID;
                                if (pVal.FormTypeEx.EndsWith("_SalesOrder"))/*订单根据"预计销售金额"显示发送人   5w以下--客服；5w-10w--主管；10w以上--经理  by WangPeng 2012年9月24日 16:16:10*/
                                {
                                    #region 根据预计销售金额分配客服   9-客服，4-主管，7经理    暂时未找到更好的解决办法
                                    Dictionary<string, string> Dic_Service = new Dictionary<string, string>();
                                    Dic_Service.Add("A", "T1.position=9");
                                    Dic_Service.Add("B", "T1.position=4");
                                    Dic_Service.Add("C", "T1.position=7");
                                    #endregion
                                    SAPbouiCOM.Form curForm = SBOApp.Forms.Item(ParentUID);
                                    string TableName_Main = (curForm.Items.Item("3").Specific as SAPbouiCOM.EditText).DataBind.TableName;
                                    string TableName_Cargo = TableName_Main.Remove(8, 1) + "1";
                                    SAPbouiCOM.DBDataSource dbds_Cargo = curForm.DataSources.DBDataSources.Item(TableName_Cargo);
                                    string SalesLevel = dbds_Cargo.GetValue("U_SalesLevel", dbds_Cargo.Offset).Trim();
                                    SalesLevel = string.IsNullOrEmpty(SalesLevel) ? "A" : SalesLevel;
                                    #region 部门上区分海运、空运、陆运
                                    string DepartmentCode = string.Empty;
                                    if (TableName_Main.IndexOf("FF") > 0)
                                    {
                                        DepartmentCode = " T1.dept IN(7,8,15) ";
                                    }
                                    else if (TableName_Main.IndexOf("SE") > 0)
                                    {
                                        DepartmentCode = " T1.dept IN(10,11,12) ";
                                    }
                                    else if (TableName_Main.IndexOf("LN") > 0)
                                    {
                                        DepartmentCode = " T1.dept IN(14) ";
                                    }
                                    #endregion
                                    messageForm.DataSources.UserDataSources.Item("Sch_Pars").Value = string.Format(" AND {0} AND {1}", Dic_Service[SalesLevel], DepartmentCode);
                                }
                            }
                            else
                            {
                                SBOApp.MessageBox("请在批准状态下进行发送。");
                            }
                        }
                        else
                        {
                            SBOApp.StatusBar.SetText("请先保存当前单据", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        void CommonEvents_B1MenuEvent(SAPBoAddon.B1AddonBase.B1MenuEvent pVal, ref bool BubbleEvent)
        {
            try
            {
                if (!SBOApp.Forms.ActiveForm.IsSystem)
                {
                    #region Add-On窗体
                    if (pVal.BeforeAction)
                    {
                        #region 数据所有权控制
                        //数据所有权控制
                        Utils.MenuAuthority(pVal, SBOApp.Forms.ActiveForm, SBOApp.Forms.ActiveForm.BusinessObject.Type, ref BubbleEvent);
                        #endregion
                        #region 窗体的取消菜单
                        //取消
                        if (pVal.MenuUID == "1284")
                        {
                            if (SBOApp.MessageBox("是否要取消此单据？", 2, "是", "否") == 2)
                                BubbleEvent = false;
                            else
                            {
                                if (FormTypes.Contains(SBOApp.Forms.ActiveForm.TypeEx))
                                {
                                    CancelOrder();
                                }
                            }
                        }
                        #endregion
                        #region 窗体的恢复菜单
                        //恢复
                        if (pVal.MenuUID == "1285")
                        {
                            if (SBOApp.MessageBox("是否要恢复已取消的单据？", 2, "是", "否") == 2)
                                BubbleEvent = false;
                            else
                            {
                                if (FormTypes.Contains(SBOApp.Forms.ActiveForm.TypeEx))
                                {
                                    RecoverOrder();
                                }
                            }
                        }
                        #endregion
                        #region 预览
                        if (pVal.MenuUID == SAPBoAddon.B1AddonBase.B1MenuUIDs.sys_PrintView)
                        {
                            this.GetPrintTemplateFile();
                            BubbleEvent = false;
                        }
                        #endregion
                    }
                    else
                    {
                        #region 窗体转换为添加时获取流水码
                        //添加
                        if (pVal.MenuUID == B1MenuTypes.sys_Add)
                        {
                            //获取流水码
                            SerialNumber.GetInstance().GetSerialNumberByProc(SBOApp.Forms.ActiveForm);
                        }
                        #endregion
                        #region 取消恢复
                        //取消、恢复
                        if (pVal.MenuUID == "1284" || pVal.MenuUID == "1285")
                        {
                            if (FormTypes.Contains(SBOApp.Forms.ActiveForm.TypeEx))
                            {
                                FindForm();
                            }
                        }
                        #endregion
                        #region  复制
                        //复制
                        if (pVal.MenuUID == "1287")
                        {
                            SAPbobsCOM.Recordset rs = GetRecordset();
                            rs.DoQuery(String.Format("select AutoKey from ONNM With(UPDLOCK) where ObjectCode = '{0}'", SBOApp.Forms.ActiveForm.BusinessObject.Type));
                            if (rs.RecordCount > 0)
                            {
                                string docEntry = rs.Fields.Item("AutoKey").Value.ToString().Trim();
                                foreach (SAPbouiCOM.DBDataSource dbds in SBOApp.Forms.ActiveForm.DataSources.DBDataSources)
                                {
                                    for (int i = 0; i < dbds.Size; i++)
                                    {
                                        dbds.SetValue("DocEntry", i, docEntry);
                                    }
                                    if (!new System.Text.RegularExpressions.Regex(@"\d+\b").Match(dbds.TableName).Success)//更新DBDS主表
                                    {
                                        dbds.SetValue("U_Status", dbds.Offset, "P");//置为计划状态
                                        string Operator = Utils.GetCurrentUser().Operator; ;
                                        dbds.SetValue("U_Operator", dbds.Offset, Operator);
                                        Utils.SelectShowEmpId(dbds, Operator, false);
                                        dbds.SetValue("U_DocDate", dbds.Offset, DateTime.Now.ToString("yyyyMMdd"));
                                        dbds.SetValue("UserSign", dbds.Offset, SBOCompany.UserSignature.ToString());
                                        //SBOApp.Forms.ActiveForm.Items.Item(SBOApp.Forms.ActiveForm.ActiveItem).Update();                                        
                                    }
                                }
                                SerialNumber.GetInstance().GetSerialNumberByProc(SBOApp.Forms.ActiveForm);
                                SBOApp.MessageBox("单据复制成功，请继续！");
                            }
                        }
                        #endregion
                        #region 打开审批窗体
                        //审批窗体
                        if (pVal.MenuUID == "1280001")
                        {
                            if (SBOApp.Forms.ActiveForm.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE)//改为只有OK状态下才能审批（By Webb.Wen At 2012-03-05 11:10:42）
                            {
                                OpenApprovalForm(ref  BubbleEvent);
                            }
                        }
                        #endregion
                        #region 驳回
                        if (pVal.MenuUID == "1280002")
                        {
                            ApprovalReturn();
                        }
                        #endregion
                        //移除菜单
                        RemoveRightClickMenus();
                    }
                    #endregion
                }
                else
                {
                    if (pVal.BeforeAction)
                    {
                        #region 打印
                        if (pVal.MenuUID == SAPBoAddon.B1AddonBase.B1MenuUIDs.sys_Print)
                        {
                            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
                            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                            rs.DoQuery("SELECT U_IsServer FROM [@AVA_FORMTYPES] Where U_Print = 'Y' And U_FileName = '" + oForm.Title + ".rpt'");
                            if (rs.RecordCount > 0)
                            {
                                if (rs.Fields.Item("U_IsServer").Value == "Y")
                                {
                                    SBOApp.SetStatusBarMessage("[Add-On]请点击选择打印模板窗体的打印按钮进行打印。");
                                    BubbleEvent = false;
                                }
                            }
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        void CommonEvents_B1RightClickEvent(SAPBoAddon.B1AddonBase.B1ContextMenuInfo eventInfo, ref bool BubbleEvent)
        {
            if (eventInfo.BeforeAction)
            {
                if (eventInfo.EventType == SAPbouiCOM.BoEventTypes.et_RIGHT_CLICK)
                {
                    //添加菜单
                    AddRightClickMenus();
                }
            }
        }
        #endregion
        #region Methods
        #region 下拉列表框处理
        /// <summary>
        /// 下拉列表框的处理
        /// </summary>
        /// <param name="FormType"></param>
        /// <param name="FormUID"></param>
        /// <param name="ItemUID"></param>
        /// <param name="ColUID"></param>
        /// <param name="Row"></param>
        private void ComboBoxHandle(string FormType, string FormUID, string ItemUID, string ColUID, int Row)
        {
            SAPbouiCOM.ComboBox cmb;
            if (string.IsNullOrEmpty(ColUID))
            {
                cmb = SBOApp.Forms.Item(FormUID).Items.Item(ItemUID).Specific;
                if (cmb.Selected == null)
                {
                    return;
                }
                if (cmb.Selected.Value.ToLower() != "new") return;
            }
            else
            {
                SAPbouiCOM.Matrix mtx = SBOApp.Forms.Item(FormUID).Items.Item(ItemUID).Specific;
                cmb = mtx.Columns.Item(ColUID).Cells.Item(Row).Specific;
                if (cmb.Selected.Value.ToLower() != "new") return;
            }
            SAPbobsCOM.Recordset ors;
            string SQL = string.Empty;
            SQL = "SELECT U_FormType,U_MenuUID,U_ItemUID,U_ColUID,U_ObjectName,U_Value,U_Desc,U_DefaultValue,U_Where FROM [@AVA_CmbNewValue] Where U_FormType = '{0}' And U_ItemUID = '{1}' And ISNULL(U_ColUID,'') = '{2}'";
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            ors.DoQuery(string.Format(SQL, FormType, ItemUID, ColUID));
            if (ors.RecordCount > 0)
            {
                OpenListFormHandle(FormUID, ItemUID, ColUID, Row,
                    ors.Fields.Item("U_MenuUID").Value,
                    ors.Fields.Item("U_ObjectName").Value,
                    ors.Fields.Item("U_Value").Value,
                    ors.Fields.Item("U_Desc").Value,
                    ors.Fields.Item("U_DefaultValue").Value,
                    ors.Fields.Item("U_Where").Value);
            }
            else
                cmb.Select("", SAPbouiCOM.BoSearchKey.psk_ByValue);
        }
        /// <summary>
        /// 打开下拉列表框所指定的窗体
        /// </summary>
        /// <param name="FormUID"></param>
        /// <param name="ItemUID"></param>
        /// <param name="ColUID"></param>
        /// <param name="Row"></param>
        /// <param name="MenuUID"></param>
        /// <param name="ObjectName"></param>
        /// <param name="Value"></param>
        /// <param name="Desc"></param>
        /// <param name="DefaultValue"></param>
        /// <param name="Where"></param>
        private void OpenListFormHandle(string FormUID, string ItemUID, string ColUID, int Row, string MenuUID, string ObjectName, string Value, string Desc, string DefaultValue, string Where)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.Form oChildForm;
            string SelectedValue = string.Empty;
            oForm = SBOApp.Forms.Item(FormUID);
            SBOApp.ActivateMenuItem(MenuUID);
            oChildForm = SBOApp.Forms.ActiveForm;

            CreateChildFormValue(oForm, oChildForm, ItemUID, ColUID, Row, ObjectName, Value, Desc, DefaultValue, Where);           
        }
        /// <summary>
        /// 列表子窗体处理
        /// </summary>
        /// <param name="ParentForm"></param>
        /// <param name="ChildForm"></param>
        /// <param name="ItemUID"></param>
        /// <param name="ColUID"></param>
        private void CreateChildFormValue(SAPbouiCOM.Form ParentForm, SAPbouiCOM.Form ChildForm, string ItemUID, string ColUID, int Row, string ObjectName, string Value, string Description, string DefaultValue, string Where)
        {
            ChildForm.Freeze(true);
            ChildForm.DataSources.UserDataSources.Add("IsCmbForm", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 1);
            ChildForm.DataSources.UserDataSources.Add("ParentID", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("ItemType", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("ItemUID", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("ColUID", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("Row", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 8);
            ChildForm.DataSources.UserDataSources.Add("ObjectName", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("Value", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("Desc", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("Default", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
            ChildForm.DataSources.UserDataSources.Add("Where", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 100);

            ChildForm.DataSources.UserDataSources.Item("IsCmbForm").ValueEx = "Y";
            ChildForm.DataSources.UserDataSources.Item("ParentID").ValueEx = ParentForm.UniqueID;
            ChildForm.DataSources.UserDataSources.Item("ItemType").ValueEx = ParentForm.Items.Item(ItemUID).Type.ToString();
            ChildForm.DataSources.UserDataSources.Item("ItemUID").ValueEx = ItemUID;
            ChildForm.DataSources.UserDataSources.Item("ColUID").ValueEx = ColUID;
            ChildForm.DataSources.UserDataSources.Item("Row").ValueEx = Row.ToString();
            ChildForm.DataSources.UserDataSources.Item("ObjectName").ValueEx = ObjectName;
            ChildForm.DataSources.UserDataSources.Item("Value").ValueEx = Value;
            ChildForm.DataSources.UserDataSources.Item("Desc").ValueEx = Description;
            ChildForm.DataSources.UserDataSources.Item("Default").ValueEx = DefaultValue;
            ChildForm.DataSources.UserDataSources.Item("Where").ValueEx = Where;
            ChildForm.Freeze(false);
        }
        /// <summary>
        /// 列表对象窗体关闭时
        /// </summary>
        /// <param name="FormUID"></param>
        private void ComboBoxListFormClose(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.Form oParentForm;
            string IsCmbForm, ParentID, ItemType, ItemUID, ColUID, Row, ObjectName, Value, Description, DefaultValue, Where;
            oForm = SBOApp.Forms.Item(FormUID);
            try
            {

                #region 判断当前窗体是否是由下拉列表框的“新建”打开的

#if DEBUG
                //add by webb.wen at 2011-12-01 16:27:12
                bool exist = false;
                System.Collections.IEnumerator enumerator = oForm.DataSources.UserDataSources.GetEnumerator();
                if (enumerator == null) return;

                while (enumerator.MoveNext())
                {
                    if ((enumerator.Current as SAPbouiCOM.UserDataSource).UID == "IsCmbForm")
                    {
                        exist = true;
                        break;
                    }
                }
                if (!exist)
                {
                    return;
                }
                /**************************************************************************/

#endif
                #endregion
                IsCmbForm = oForm.DataSources.UserDataSources.Item("IsCmbForm").ValueEx;
                if (IsCmbForm == "Y")
                {
                    ParentID = oForm.DataSources.UserDataSources.Item("ParentID").ValueEx;
                    ItemType = oForm.DataSources.UserDataSources.Item("ItemType").ValueEx;
                    ItemUID = oForm.DataSources.UserDataSources.Item("ItemUID").ValueEx;
                    ColUID = oForm.DataSources.UserDataSources.Item("ColUID").ValueEx;
                    Row = oForm.DataSources.UserDataSources.Item("Row").ValueEx;
                    ObjectName = oForm.DataSources.UserDataSources.Item("ObjectName").ValueEx;
                    Value = oForm.DataSources.UserDataSources.Item("Value").ValueEx;
                    Description = oForm.DataSources.UserDataSources.Item("Desc").ValueEx;
                    DefaultValue = oForm.DataSources.UserDataSources.Item("Default").ValueEx;
                    Where = oForm.DataSources.UserDataSources.Item("Where").ValueEx;

                    oParentForm = SBOApp.Forms.Item(ParentID);
                    if (ItemType == SAPbouiCOM.BoFormItemTypes.it_COMBO_BOX.ToString())
                    {
                        SAPbouiCOM.ComboBox oCombo = oParentForm.Items.Item(ItemUID).Specific;
                        oCombo.SelectExclusive("", SAPbouiCOM.BoSearchKey.psk_ByValue);
                        Utils.InitialItemComboBox(this.SBOCompany, oParentForm.Items.Item(ItemUID), Value, Description, ObjectName, null, DefaultValue, Where);
                    }
                    else
                    {
                        SAPbouiCOM.ComboBox oCombo = oParentForm.Items.Item(ItemUID).Specific.Columns.Item(ColUID).Cells.Item(int.Parse(Row)).Specific;
                        oCombo.SelectExclusive("", SAPbouiCOM.BoSearchKey.psk_ByValue);

                        Utils.InitialMatrixComboBox(this.SBOCompany, oParentForm.Items.Item(ItemUID).Specific, ColUID, Value, Description, ObjectName, null, DefaultValue.ToUpper() == "Field".ToUpper() ? string.Empty : DefaultValue, Where);
                    }
                }

            }
            catch
            {
#if DEBUG
                TimeSpan ts = DateTime.Now - CurrentDatetime;
                SBOApp.SetStatusBarMessage("运行时间：" + ts.TotalMilliseconds.ToString(), SAPbouiCOM.BoMessageTime.bmt_Short, false);
#endif
                return;
            }

        }
        #endregion
        #region 单击确定按钮
        private void ClickOkButton(ref bool BubbleEvent)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
            if (oForm.IsSystem) return;
            if (oForm.TypeEx == "AVA_ApprovalStep") return;//审批
            if (oForm.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE || oForm.Mode == SAPbouiCOM.BoFormMode.fm_VIEW_MODE)
            {
                if (SBOApp.MessageBox("是否关闭当前窗体？", 2, "是", "否") == 2)
                    BubbleEvent = false;
            }
        }
        #endregion
        #region Orderhandler
        /// <summary>
        /// 取消单据
        /// </summary>
        private void CancelOrder()
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SAPbouiCOM.Item oItem = oForm.Items.Item(oForm.DataBrowser.BrowseBy);
            string TableName = oItem.Specific.DataBind.TableName;
            string DocEntry = oItem.Specific.Value;
            ors.DoQuery("UPDATE [" + TableName + "] SET U_Status = 'D' Where DocEntry = " + DocEntry);

            oForm.DataSources.UserDataSources.Item("LastEntry").Value = DocEntry;
        }
        /// <summary>
        /// 恢复被取消的单据
        /// </summary>
        private void RecoverOrder()
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SAPbouiCOM.Item oItem = oForm.Items.Item(oForm.DataBrowser.BrowseBy);
            string TableName = oItem.Specific.DataBind.TableName;
            string DocEntry = oItem.Specific.Value;
            ors.DoQuery("UPDATE [" + TableName + "] SET U_Status = 'P' Where DocEntry = " + DocEntry);

            oForm.DataSources.UserDataSources.Item("LastEntry").Value = DocEntry;
        }
        #endregion
        #region 查找窗体
        /// <summary>
        /// 查找窗体
        /// </summary>
        private void FindForm()
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
            if (oForm.Mode != SAPbouiCOM.BoFormMode.fm_FIND_MODE)
                oForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
            oForm.Items.Item("3").Enabled = true;
            oForm.Items.Item("3").Specific.Value = oForm.DataSources.UserDataSources.Item("LastEntry").Value;
            oForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Collapsed);
        }
        #endregion
        #region 菜单
        /// <summary>
        /// 添加右击菜单 
        /// </summary>
        /// <remarks></remarks>
        private void AddRightClickMenus()
        {
            SAPbouiCOM.Form oForm;
            oForm = SBOApp.Forms.ActiveForm;
            if (oForm.IsSystem) return;

            SAPbouiCOM.MenuItem oMenuItem = default(SAPbouiCOM.MenuItem);
            SAPbouiCOM.Menus oMenus = default(SAPbouiCOM.Menus);
            SAPbouiCOM.MenuCreationParams oCreationPackage = default(SAPbouiCOM.MenuCreationParams);
            string Status = string.Empty;
            try
            {
                if (FormTypes.Contains(oForm.TypeEx))
                {
                    //获取单据的状态
                    Status = GetCurrentFormStatus(oForm);
                    #region 发起审批
                    //判断是否存在审批
                    if (GetExistsAppravol(oForm.TypeEx))
                    {
                        if (Status == "P")
                        {
                            oCreationPackage = SBOApp.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_MenuCreationParams);
                            oCreationPackage.Type = SAPbouiCOM.BoMenuType.mt_STRING;
                            oCreationPackage.UniqueID = "1280001";
                            oCreationPackage.String = "发起审批";
                            oCreationPackage.Enabled = true;

                            oMenuItem = SBOApp.Menus.Item("1280");
                            oMenus = oMenuItem.SubMenus;
                            if (!oMenus.Exists("1280001"))
                            {
                                oMenus.AddEx(oCreationPackage);
                            }
                        }
                    }
                    #endregion
                    #region 驳回
                    if (Status == "R")
                    {
                        oCreationPackage = SBOApp.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_MenuCreationParams);
                        oCreationPackage.Type = SAPbouiCOM.BoMenuType.mt_STRING;
                        oCreationPackage.UniqueID = "1280002";
                        oCreationPackage.String = "取消批准";
                        oCreationPackage.Enabled = true;

                        oMenuItem = SBOApp.Menus.Item("1280");
                        oMenus = oMenuItem.SubMenus;
                        if (!oMenus.Exists("1280002"))
                        {
                            oMenus.AddEx(oCreationPackage);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取对象是否已配置审批流程
        /// </summary>
        /// <param name="FormType"></param>
        private bool GetExistsAppravol(string FormType)
        {
            string SQL = string.Empty;
            SAPbobsCOM.Recordset ors;
            try
            {
                ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                SQL = "select COUNT(U_TransType) from [@AVA_WTM3] Where U_TransType = '{0}'";
                ors.DoQuery(string.Format(SQL, FormType));
                if (ors.Fields.Item(0).Value > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 获取当前窗体的窗体状态
        /// </summary>
        /// <param name="oForm"></param>
        /// <returns></returns>
        private string GetCurrentFormStatus(SAPbouiCOM.Form oForm)
        {
            SAPbouiCOM.DBDataSource dbds;
            string PrimaryKey = string.Empty;
            string TableName = string.Empty;
            try
            {
                PrimaryKey = oForm.DataBrowser.BrowseBy;
                if (string.IsNullOrEmpty(PrimaryKey))
                {
                    return string.Empty;
                }
                TableName = oForm.Items.Item(PrimaryKey).Specific.DataBind.TableName;
                if (string.IsNullOrEmpty(TableName)) return "";
                dbds = oForm.DataSources.DBDataSources.Item(TableName);
                return dbds.GetValue("U_Status", dbds.Offset).Trim();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 移除右击菜单 
        /// </summary>
        /// <remarks></remarks>
        private void RemoveRightClickMenus()
        {
            try
            {
                #region 发起审批
                if (SBOApp.Menus.Exists("1280001"))
                {
                    SBOApp.Menus.RemoveEx("1280001");
                }
                #endregion
                #region 驳回
                if (SBOApp.Menus.Exists("1280002"))
                {
                    SBOApp.Menus.RemoveEx("1280002");
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 弹出审批窗体
        /// <summary>
        /// 弹出审批窗体
        /// </summary>
        private void OpenApprovalForm(ref bool BubbleEvent)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            oForm = SBOApp.Forms.ActiveForm;
            dynamic Item = oForm.Items.Item(oForm.DataBrowser.BrowseBy).Specific;
            dbds = oForm.DataSources.DBDataSources.Item(Item.DataBind.TableName);
            SAPbouiCOM.Form oChildForm;
            string SQL;
            SAPbobsCOM.Recordset ors;
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            //判断窗体的字段是否为空
            if (ControlOrderEmpty(SBOApp.Forms.ActiveForm, ref BubbleEvent, "R") == false)
            {
                return;
            }
            SQL = @"select top 1 T2.U_AppCode Code,T2.U_AppName,T2.U_AppCode,T1.U_WstCode,T1.U_WstName
                            from [@AVA_WTM3] T0
                                INNER JOIN [@AVA_WTM2] T1 ON T0.Code = T1.Code
                                INNER JOIN [@AVA_OWTM] T2 ON T0.Code = T2.Code
                                LEFT JOIN [@AVA_WTM1] T3 ON T2.Code = T3. Code
                                INNER JOIN [OUSR] T4 ON T3.U_UserID = T4.USERID
                            Where U_TransType = '{0}' And T4.USER_CODE = '{1}' 
                            order by cast(T0.code as int) desc";
            ors.DoQuery(String.Format(SQL, oForm.TypeEx, SBOCompany.UserName));
            if (ors.RecordCount <= 0)
            {
                SBOApp.MessageBox("此账户或是单据没有配置审批模板，此单据不需要审批。");
                return;
            }
            if (dbds.GetValue("U_Status", dbds.Offset).Trim() != "P")
            {
                SBOApp.MessageBox("此单据不是计划状态的，不需要进行审批。");
                return;
            }
            oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_ApprovalStepForm.srf", "", true);
            #region 设置主了窗体UID
            //oForm.DataSources.UserDataSources.Item("ChildUID").Value = oChildForm.UniqueID;
            oChildForm.DataSources.UserDataSources.Item("ParentUID").Value = oForm.UniqueID;
            #endregion
            oChildForm.Mode = SAPbouiCOM.BoFormMode.fm_ADD_MODE;


            SAPbouiCOM.DBDataSource oChilddbds = oChildForm.DataSources.DBDataSources.Item("@AVA_OWDD");
            ors.DoQuery("SELECT Autokey FROM ONNM  Where ObjectCode = 'AVA_ApprovalStep'");
            oChilddbds.SetValue("DocEntry", oChilddbds.Offset, ors.Fields.Item("Autokey").Value.ToString());//DocEntry
            #region 单据信息
            #region 创建人
            SAPbouiCOM.ComboBox oCmb;
            oCmb = oChildForm.Items.Item("9").Specific;
            oCmb.ValidValues.Add(SBOCompany.UserSignature.ToString(), SBOCompany.UserName);
            oChilddbds.SetValue("U_OwnerID", oChilddbds.Offset, SBOCompany.UserSignature.ToString());//创建人
            #endregion
            oChilddbds.SetValue("U_DocDate", oChilddbds.Offset, DateTime.Now.ToString("yyyyMMdd"));//申请日期
            oChilddbds.SetValue("U_Status", oChilddbds.Offset, "P");//单据状态
            #region 订单类型
            oCmb = oChildForm.Items.Item("11").Specific;
            ors.DoQuery("select Name from OUDO Where Code = '" + oForm.TypeEx + "'");
            oCmb.ValidValues.Add(oForm.TypeEx, ors.Fields.Item("Name").Value.ToString());
            oChilddbds.SetValue("U_OrderType", oChilddbds.Offset, oForm.TypeEx);//订单类型
            #endregion
            oChilddbds.SetValue("U_OrderDate", oChilddbds.Offset, dbds.GetValue("U_DocDate", dbds.Offset).Trim());
            oChilddbds.SetValue("U_DocEntry", oChilddbds.Offset, dbds.GetValue("DocEntry", dbds.Offset).Trim());
            oChilddbds.SetValue("U_SerialNum", oChilddbds.Offset, dbds.GetValue("U_SerialNum", dbds.Offset).Trim());
            #endregion
            #region 审批模板
            SQL = @"select top 1 T2.U_AppCode Code,T2.U_AppName,T2.U_AppCode,T1.U_WstCode,T1.U_WstName
                                from [@AVA_WTM3] T0
	                                INNER JOIN [@AVA_WTM2] T1 ON T0.Code = T1.Code
	                                INNER JOIN [@AVA_OWTM] T2 ON T0.Code = T2.Code
                                Where U_TransType = '{0}' order by cast(T0.code as int) desc";
            ors.DoQuery(string.Format(SQL, oForm.TypeEx));
            #region 审批模板
            oCmb = oChildForm.Items.Item("7").Specific;
            oCmb.ValidValues.Add(ors.Fields.Item("Code").Value, ors.Fields.Item("U_AppName").Value);
            oChilddbds.SetValue("U_WtmCode", oChilddbds.Offset, ors.Fields.Item("Code").Value);
            #endregion
            #region 审批阶段
            oCmb = oChildForm.Items.Item("21").Specific;
            oCmb.ValidValues.Add(ors.Fields.Item("U_WstCode").Value, ors.Fields.Item("U_WstName").Value);
            oChilddbds.SetValue("U_WstCode", oChilddbds.Offset, ors.Fields.Item("U_WstCode").Value);
            #endregion
            #endregion
        }
        #endregion
        #region 控制单据状态
        private void ControlOrderStatus()
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.ActiveForm;
            if (oForm.Mode == SAPbouiCOM.BoFormMode.fm_FIND_MODE) return;
            SAPbouiCOM.ComboBox oCmb = oForm.Items.Item("7").Specific;
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(oCmb.DataBind.TableName);
            string Status = dbds.GetValue("U_Status", dbds.Offset).Trim();
            if (Status != "R" && Status != "D" && Status != "A")
            {
                dbds.SetValue("U_Status", dbds.Offset, "P");
                SBOApp.SetStatusBarMessage("在操作状态下，只能选择已审核、已批准或作废状态。", SAPbouiCOM.BoMessageTime.bmt_Short, false);
                oForm.Mode = CurrentFormMode;
            }
        }
        #endregion
        #region 保存数据时控制哪些字段不允许为空
        /// <summary>
        /// 根据配置的字段判断在特定的状态下是否允许字段为空
        /// </summary>
        /// <param name="BubbleEvent"></param>
        private bool ControlOrderEmpty(SAPbouiCOM.Form oForm, ref bool BubbleEvent, string Status = null)
        {
            if (SBOApp.Forms.ActiveForm.IsSystem)
                return false;
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);//记录集
            string SQL = string.Empty;
            string ObjectType = oForm.TypeEx;//字段窗体的类型
            SQL = "SELECT count(*) FROM [@AVA_OCNT] Where U_ObjectType='{0}'";
            ors.DoQuery(string.Format(SQL, ObjectType));
            if (ors.Fields.Item(0).Value < 1)
                return true;
            string ItemUID = oForm.DataBrowser.BrowseBy;//浏览字段
            string TableName = oForm.Items.Item(ItemUID).Specific.DataBind.TableName;//浏览字段所对应的表
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item(TableName);//数据对象
            if (string.IsNullOrEmpty(Status))
            {
                Status = dbds.GetValue("U_Status", dbds.Offset).Trim();//当前窗体的状态
            }
            //添加海运和空运的特殊判断
            bool Direct = false;
            if (oForm.TypeEx == B1FormTypes.ado_AVA_FF_BusinessOperation || oForm.TypeEx == B1FormTypes.ado_AVA_SE_BusinessOperation)
            {
                Direct = dbds.GetValue("U_IsDBL", dbds.Offset).Trim() == "Y" ? true : false;
            }
            string Field = string.Empty;//字段
            string FieldName = string.Empty;//字段名称
            string IsEmpty = string.Empty;//允许为空
            string IsCheckChild = string.Empty;//检查子项
            string ChildObjectType = string.Empty;//子项对象类型
            //获取当前窗体类型的特定状态在【@AVA_OCNT】表的配置信息
            if (Direct)
            {
                if (oForm.TypeEx == B1FormTypes.ado_AVA_SE_BusinessOperation)
                    SQL = @"SELECT U_TableName,U_Status,U_Field,U_FieldName,U_IsEmpty,U_IsCheckChild,U_ChildObjectType 
                        FROM [@AVA_OCNT] 
                        Where U_ObjectType = '{0}' And U_Status = '{1}'
                            And U_TableName <> '@AVA_SE_BNO4'
                        ";
                if (oForm.TypeEx == B1FormTypes.ado_AVA_FF_BusinessOperation)
                    SQL = @"SELECT U_TableName,U_Status,U_Field,U_FieldName,U_IsEmpty,U_IsCheckChild,U_ChildObjectType 
                        FROM [@AVA_OCNT] 
                        Where U_ObjectType = '{0}' And U_Status = '{1}'
                            And U_TableName <> '@AVA_FF_BNO4'
                        ";
            }
            else
                SQL = "SELECT U_TableName,U_Status,U_Field,U_FieldName,U_IsEmpty,U_IsCheckChild,U_ChildObjectType FROM [@AVA_OCNT] Where U_ObjectType = '{0}' And U_Status = '{1}'";
            ors.DoQuery(string.Format(SQL, ObjectType, Status));
            for (int i = 0; i < ors.RecordCount; i++)
            {
                TableName = ors.Fields.Item("U_TableName").Value;//获取配置表中定义的数据表
                dbds = oForm.DataSources.DBDataSources.Item(TableName);//数据对象
                Field = ors.Fields.Item("U_Field").Value;//字段
                FieldName = ors.Fields.Item("U_FieldName").Value;//字段名称
                IsEmpty = ors.Fields.Item("U_IsEmpty").Value;//允许为空
                IsCheckChild = ors.Fields.Item("U_IsCheckChild").Value;//检查子项
                ChildObjectType = ors.Fields.Item("U_ChildObjectType").Value;//子项对象类型
                //判断此对象是否只有一条记录，如果有金条记录，则逐条进行判断
                if (dbds.Size > 1)
                {
                    #region 多条记录检查
                    for (int j = 0; j < dbds.Size; j++)
                    {
                        if (string.IsNullOrEmpty(dbds.GetValue(Field, j).Trim()) || dbds.GetValue(Field, j).Trim() == "N")
                        {
                            //方块字段不控制
                            if (IsCheckChild == "N" || string.IsNullOrEmpty(IsCheckChild))
                            {
                                BubbleEvent = false;
                                SBOApp.MessageBox(FieldName + " 数据项不允许为空，请检查！");
                                return false;
                            }
                        }
                        else
                        {
                            //检查子项
                            if (IsCheckChild == "Y" && dbds.GetValue(Field, dbds.Offset).Trim() == "Y")
                                CheckChildFieldIsEmpty(ref BubbleEvent, Status, FieldName, ChildObjectType, dbds.GetValue("DocEntry", j).Trim());
                        }
                    }
                    #endregion
                }
                else
                {
                    if (dbds.Size == 0)
                    {
                        BubbleEvent = false;
                        SBOApp.MessageBox(FieldName + " 数据项不允许为空，请检查！");
                        return false;
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(dbds.GetValue(Field, dbds.Offset).Trim()) || dbds.GetValue(Field, dbds.Offset).Trim() == "N")
                        {
                            //方块字段不控制
                            if (dbds.GetValue(Field, dbds.Offset).Trim() == "N" && IsEmpty == "N")//IsCheckChild == "Y" || string.IsNullOrEmpty(IsCheckChild)
                            {
                                BubbleEvent = false;
                                SBOApp.MessageBox(FieldName + " 数据项不允许为空，请检查！");
                                return false;
                            }
                        }
                        else
                        {
                            //检查子项
                            if (IsCheckChild == "Y" && dbds.GetValue(Field, dbds.Offset).Trim() == "Y")
                                CheckChildFieldIsEmpty(ref BubbleEvent, Status, FieldName, ChildObjectType, dbds.GetValue("DocEntry", dbds.Offset).Trim());
                        }
                    }
                }
                ors.MoveNext();
            }
            return true;
        }
        /// <summary>
        /// 检查方块里的数据项
        /// </summary>
        /// <param name="BubbleEvent"></param>
        /// <param name="Status"></param>
        /// <param name="ObjectTypeName"></param>
        /// <param name="ObjectType"></param>
        /// <param name="BaseEntry"></param>
        /// <returns></returns>
        private bool CheckChildFieldIsEmpty(ref bool BubbleEvent, string Status, string ObjectTypeName, string ObjectType, string BaseEntry)
        {
            string SQL = string.Empty;
            string Field = string.Empty;//字段
            string FieldName = string.Empty;//字段名称
            string TableName = string.Empty;//表;
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);//记录集  
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            //获取当前窗体类型的特定状态在【@AVA_OCNT】表的配置信息
            SQL = "SELECT U_TableName,U_Status,U_Field,U_FieldName,U_IsEmpty FROM [@AVA_OCNT] Where U_IsEmpty <> 'Y' And U_ObjectType = '{0}' And U_Status = '{1}'";
            ors.DoQuery(string.Format(SQL, ObjectType, Status));

            for (int i = 0; i < ors.RecordCount; i++)
            {
                TableName = ors.Fields.Item("U_TableName").Value;//获取配置表中定义的数据表
                Field = ors.Fields.Item("U_Field").Value;//字段
                FieldName = ors.Fields.Item("U_FieldName").Value;//字段名称
                SQL = "SELECT {0} FROM [{1}] Where U_BaseEntry = {2}";
                SQL = string.Format(SQL, Field, TableName, BaseEntry);
                rs.DoQuery(SQL);
                if (rs.RecordCount <= 0)
                {
                    BubbleEvent = false;
                    SBOApp.MessageBox(ObjectTypeName + " 方块里的数据项不允许为空，请检查！");
                    return false;
                }

                //判断此对象是否只有一条记录，如果有金条记录，则逐条进行判断
                string item;
                item = rs.Fields.Item(Field).Value.ToString();
                decimal d;
                if (decimal.TryParse(item, out d))
                {
                    if (d == 0)
                    {
                        BubbleEvent = false;
                        SBOApp.MessageBox(ObjectTypeName + " 页签下 " + FieldName + " 数据项不允许为空，请检查！");
                        return false;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(item))
                    {
                        BubbleEvent = false;
                        SBOApp.MessageBox(ObjectTypeName + " 页签下 " + FieldName + " 数据项不允许为空，请检查！");
                        return false;
                    }
                }
                ors.MoveNext();
            }
            return true;
        }
        #endregion
        #region 审批驳回
        /// <summary>
        /// 审批驳回
        /// </summary>
        private void ApprovalReturn()
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            string PrimaryKey = string.Empty;
            string TableName = string.Empty;
            string UserCode = string.Empty;
            try
            {
                oForm = SBOApp.Forms.ActiveForm;
                PrimaryKey = oForm.DataBrowser.BrowseBy;
                TableName = oForm.Items.Item(PrimaryKey).Specific.DataBind.TableName;
                dbds = oForm.DataSources.DBDataSources.Item(TableName);
                #region 不合理，注释  by WangPeng 2012年8月6日 19:02:09
                //UserCode = string.IsNullOrEmpty(dbds.GetValue("U_Appraiser", dbds.Offset).Trim()) ? dbds.GetValue("UserSign", dbds.Offset).Trim() : dbds.GetValue("U_Appraiser", dbds.Offset).Trim();
                //if (SBOCompany.UserSignature.ToString() != UserCode)
                //{
                //    SBOApp.MessageBox("此单据已审批，您没有权限！");
                //    return;
                //}
                #endregion
                oForm.Mode = SAPbouiCOM.BoFormMode.fm_UPDATE_MODE;
                dbds.SetValue("U_Status", dbds.Offset, "P");
                if (new string[] { "@AVA_FF_OBNO", "@AVA_SE_OBNO", "@AVA_LN_OBNO", "@AVA_OR_OBNO" }.Contains(TableName))
                {
                    dbds.SetValue("U_ReceApproved", dbds.Offset, "N");
                    dbds.SetValue("U_PayApproved", dbds.Offset, "N");
                }
                oForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Collapsed);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 打印/预览
        private void GetPrintTemplateFile()
        {
            string DocEntry;
            string BusinessType = "";//业务类型
            SAPbouiCOM.Form toPrintForm = SBOApp.Forms.ActiveForm;
            if (toPrintForm.Mode != SAPbouiCOM.BoFormMode.fm_OK_MODE)
            {
                SBOApp.MessageBox("请保存单据后，再进行打印预览！");
                return;
            }
            DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(toPrintForm, toPrintForm.DataBrowser.BrowseBy).ToString();
            SAPbouiCOM.EditText edit = toPrintForm.Items.Item(toPrintForm.DataBrowser.BrowseBy).Specific;
            try
            {
                BusinessType = toPrintForm.DataSources.DBDataSources.Item(edit.DataBind.TableName).GetValue("U_TransportType", 0).Trim();
            }
            catch
            { }
            if (string.IsNullOrEmpty(DocEntry))
            {
                SBOApp.StatusBar.SetText("报表参数无效", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                return;
            }
            SBOApp.StatusBar.SetText("正在预览报表，请稍等.....", SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            string AcitveFormType = SBOApp.Forms.ActiveForm.TypeEx;
            string SQL_GetPrintInfo = string.Format(@"SELECT U_FormDesc,U_FileName,ISNULL(U_IsServer,'N') U_IsServer 
                                                        FROM [@AVA_FormTypes] 
                                                        Where U_Print = N'Y' And U_FormType =N'{0}' And (ISNULL(U_BusinessType,'') = N'{1}' OR ISNULL(U_BusinessType,'') = N'')", AcitveFormType, BusinessType);
            oRst.DoQuery(SQL_GetPrintInfo);
            if (oRst.RecordCount == 0)
            {
                SBOApp.StatusBar.SetText("【Add-On】该单据未配置打印模板,请在 [工具] -> [用户定义的窗口] -> [窗体类型]中配置模板", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                return;
            }
            if (oRst.RecordCount > 0)
            {
                //if (AcitveFormType == B1FormTypes.ado_AVA_SE_BusinessOperation)
                //{
                //    string TransportType = SAPBoAddon.B1Assistant.Item.GetValue(SBOApp.Forms.ActiveForm, "45").ToString();
                //    if (new ArrayList { "OE", "OI" }.Contains(TransportType))/*海运出口、海运进口*/
                //    {
                //        SQL_GetPrintInfo += string.Format(@" AND (U_FormDesc LIKE N'%{0}%' OR U_FormDesc LIKE N'%通用%')", TransportType == "OE" ? "出口" : "进口");
                //    }

                //}
                SAPbouiCOM.Form oForm_SelectTmep = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_SelectedPrintForm.srf", null);
                oForm_SelectTmep.DataSources.UserDataSources.Item("DocEntry").ValueEx = DocEntry;
                SAPbouiCOM.Grid oGrid = oForm_SelectTmep.Items.Item("Grid").Specific;
                SAPbouiCOM.DataTable oTable = default(SAPbouiCOM.DataTable);
                oTable = oForm_SelectTmep.DataSources.DataTables.Add("dt");
                oTable.ExecuteQuery(SQL_GetPrintInfo);

                oGrid.DataTable = oTable;
                oGrid.Columns.Item(0).TitleObject.Caption = "报表描述";
                oGrid.Columns.Item(1).TitleObject.Caption = "报表文件";
                oGrid.Columns.Item(2).TitleObject.Caption = "是否在服务器打印";
                oGrid.Columns.Item(0).Width = 254;
                oGrid.Columns.Item(1).Visible = false;
                oGrid.Columns.Item(2).Visible = false;
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oRst);
        }

        #endregion
        #endregion
    }
}
